package com.xyc.servlet.main;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    private String contextPath;


    @Override
    public void init(FilterConfig fc) throws ServletException {
        contextPath = fc.getServletContext().getContextPath();
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession();
        String path = request.getServletPath();
        boolean flag = isPermit(path, session);
        if (flag) {
            //不拦截
            chain.doFilter(request, response);
        } else {
            //拦截
            response.sendRedirect(contextPath + "/login.html");
        }
    }

    @Override
    public void destroy() {

    }

    //判断 是否能拦截
    public boolean isPermit(String path, HttpSession session) {
        if (null != session.getAttribute("username")) {
            return true;
        }
        if (path.endsWith("/login") || path.endsWith("login.html") || path.endsWith("/checkName")) {
            return true;
        }
        return false;
    }
}
